package com.xiaomo.gitee.datamanager.security.handler;

import com.xiaomo.gitee.datamanager.common.result.Code;
import com.xiaomo.gitee.datamanager.common.result.Result;
import com.xiaomo.gitee.datamanager.util.HttpUtils;
import com.xiaomo.gitee.datamanager.util.JwtUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

public class AuthenticationFailureHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        /*Cookie cookie = new Cookie(JwtUtils.HTTP_HEADER,null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        response.sendRedirect("/login");*/
        if (authException instanceof BadCredentialsException) {
            HttpUtils.writeJson(response,Result.fail(Integer.parseInt(Code.LOGIN_FAILED_INCORRECT_PASSWORD),Code.getInfo(Code.LOGIN_FAILED_INCORRECT_PASSWORD)));
        } else {
            HttpUtils.writeJson(response, Result.fail(Integer.parseInt(Code.AUTHENTICATION_FAILED),Code.getInfo(Code.AUTHENTICATION_FAILED)));
        }
    }
}
